<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactStage\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactStage\Contract\ContactStageContract;
use MoChat\Plugin\ContactStage\Contract\ContactStageEmployeeContract;

/**
 * 员工对客户阶段进行更改.
 *
 * Class Index.
 * @Controller
 */
class ContactStageEmployeeUpdate extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ContactStageContract
     */
    protected $contactStageService;

    /**
     * @Inject
     * @var ContactStageEmployeeContract
     */
    protected $contactStageEmployeeService;

    /**
     * @RequestMapping(path="/dashboard/contactStage/contactStageEmployeeUpdate", methods="PUT")
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        $this->validated($this->request->all());

        $param = [
            'stageId' => (int) $this->request->input('stageId', 0),
            'contactId' => (int) $this->request->input('contactId'),
            'employeeId' => (int) $this->request->input('employeeId'),
            'batch' => $this->request->input('batch', []),
        ];

        if (! empty($param['batch'])) {
            foreach ($param['batch'] as $item) {
                $this->handleStage($item['contactId'], $item['employeeId'], $param['stageId']);
            }
        } else {
            $this->handleStage($param['contactId'], $param['employeeId'], $param['stageId']);
        }

        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'stageId' => 'required | integer | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'stageId.required' => '阶段id 必填',
            'stageId.integer' => '阶段id 必须为整型',
        ];
    }

    private function handleStage(int $contactId, int $employeeId, int $stageId): array
    {
        $corpId = user()['corpIds'][0];
        $stage = $this->contactStageEmployeeService->getContactStageEmployeeByOtherId($contactId, $employeeId, $corpId);

        try {
            ($stageId > 0 && ! empty($stage)) && $this->contactStageEmployeeService->updateContactStageEmployeeById($stage['id'], ['stage_id' => $stageId]);
            $stageId === 0 && $this->contactStageEmployeeService->deleteContactStageEmployeeByContactIdEmployeeId($contactId, $employeeId);
            if ($stageId > 0 && empty($stage)) {
                $data = [
                    'corp_id' => $corpId,
                    'stage_id' => $stageId,
                    'contact_id' => $contactId,
                    'employee_id' => $employeeId,
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                $this->contactStageEmployeeService->createContactStageEmployee($data);
            }
        } catch (\Exception $e) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '修改失败');
        }
        return [];
    }
}
